package order

import (
	"context"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderListLogic {
	return &OrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderListLogic) OrderList(req *types.OrderListReq) (resp *types.OrderListRsp, err error) {
	data := make([]*models.Order, 0)
	sql := l.svcCtx.Engine.Where("")
	if req.Status > 0 {
		sql = sql.And("status=?", req.Status)
	}else if req.Status == 0 {
		// sql = sql.And("status=?", req.Status)
	} else {
		sql = sql.And("status>1")
	}
	if req.UserId > 0 {
		sql = sql.And("user_id=?", req.UserId)
	}
	if req.BusinessId > 0 {
		sql = sql.And("business_id=?", req.BusinessId)
	}
	if req.ProductId > 0 {
		sql = sql.And("product_id=?", req.ProductId)
	}
	if req.DealerId > 0 {
		sql = sql.And("dealer_id=?", req.DealerId)
	}
	count, err := sql.Desc("id").Limit(req.Size, (req.Page-1)*req.Size).FindAndCount(&data)
	if err != nil {
		return nil, err
	}
	list := make([]*types.Order, len(data), len(data))
	for i, _ := range data {
		statusStr := ""
		switch data[i].Status {
		case 1:
			statusStr = "未支付"
		case 2:
			statusStr = "已支付"
		case 3:
			statusStr = "待核销"
		case 4:
			statusStr = "已完成"
		}

		list[i] = &types.Order{
			Id:            data[i].Id,
			Code:          data[i].Code,
			UserId:        data[i].UserId,
			ProductId:     data[i].ProductId,
			Amount:        data[i].Amount,
			UserName:      data[i].UserName,
			ProductName:   data[i].ProductName,
			WriteOffCount: data[i].WriteOffCount,
			FinishCount:   data[i].FinishCount,
			Status:        data[i].Status,
			PayOrderId:    data[i].PayOrderId,
			OpenId:        data[i].OpenId,
			InviteId:      data[i].InviteId,
			ProductCover:  data[i].ProductCover,
			StatusStr:     statusStr,
			PayTime:       data[i].PayTime,
		}
	}

	return &types.OrderListRsp{
		List:  list,
		Count: count,
	}, nil
}
